﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
using DBProvider;
using DBProvider.Providers;

namespace HealthCommunity.Controls
{
	public partial class UCExamination : System.Web.UI.UserControl
	{
		private IExaminationProvider _ExaminationProvider;
		private Dictionary<int, List<ExaminationAnswer>> _DicExmtQstnExmtAswr;
		private RLT_UserAndExamination _UsersExamination;
		private List<int> _UsersExmtAswr;

		public RLT_UserAndExamination UsersExamination
		{
			get
			{
				if(_UsersExamination != null)
				{
					return _UsersExamination;
				}
				else
				{
					var user = SiteContext.Current.CurrentUser;

					if(user != null && CurrentExaminationID > 0)
					{
						if(_ExaminationProvider == null)
						{
							_ExaminationProvider = new ExaminationProvider();
						}

						var rlt_UserAndExmt = _ExaminationProvider.GetUserAndExaminationByUser(user.UserID);

						if(rlt_UserAndExmt != null && rlt_UserAndExmt.Count > 0)
						{
							_UsersExamination = rlt_UserAndExmt.SingleOrDefault(ue => ue.ExaminationID == CurrentExaminationID);
						}
					}

					return _UsersExamination;
				}
			}
		}

		public int CurrentExaminationID
		{
			get
			{
				return CommonHelper.QueryStringInt("examinationid");
			}
		}

		protected void Page_Load(object sender, EventArgs e)
		{
			if(!IsPostBack)
			{
				if(CurrentExaminationID > 0 && SiteContext.Current.CurrentUser != null)
				{
					BindCurrentExamination();
				}

				this.Page.Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
			}
		}

		protected void btnSubmit_Click(object sender, EventArgs e)
		{
			var user = SiteContext.Current.CurrentUser;

			if(user != null)
			{
				if(_ExaminationProvider == null)
				{
					_ExaminationProvider = new ExaminationProvider();
				}

				List<RLT_USERANDExaminationAnswer> lstUserAndExmtAswr = new List<RLT_USERANDExaminationAnswer>();
				var lstExmtQstn = _ExaminationProvider.GetExaminationQuestionByExamination(CurrentExaminationID);
				var lstExmtAswr = _ExaminationProvider.GetExaminationAnswerByExamination(CurrentExaminationID);
				decimal? totalScore = decimal.Zero;

				foreach(RepeaterItem item in rptExmtQstn.Items)
				{
					var rblExmtQstnAswr = item.FindControl("rblExmtQstnAswr") as RadioButtonList;
					var hfExmtQstnID = item.FindControl("hfExmtQstnID") as HiddenField;

					if(rblExmtQstnAswr != null)
					{
						var theUserAndExmtAswr = new RLT_USERANDExaminationAnswer() { UserID = user.UserID };

						var selectedItem = rblExmtQstnAswr.SelectedValue;

						if(!string.IsNullOrEmpty(selectedItem))
						{
							var selectedExmtAswrID = int.Parse(selectedItem);
							theUserAndExmtAswr.ExaminationAnswerID = selectedExmtAswrID;

							lstUserAndExmtAswr.Add(theUserAndExmtAswr);

							var theExmtQstnID = int.Parse(hfExmtQstnID.Value);

							var theExmtQstn = lstExmtQstn.SingleOrDefault(eq => eq.ExaminationQuestionID == theExmtQstnID);
							var theExmtAswr = lstExmtAswr.SingleOrDefault(ea => ea.ExaminationAnswerID == selectedExmtAswrID);

							if(theExmtAswr != null && theExmtQstn != null && theExmtQstn.ExaminationQuestionAnswer.Equals(theExmtAswr.ExaminationAnswerNum))
							{
								totalScore += theExmtQstn.ExaminationQuestionScore;
							}
						}
					}
				}

				var theUserAndExmt = new RLT_UserAndExamination() { ExaminationID = CurrentExaminationID, ExaminationTime = DateTime.Now, UserID = user.UserID, ExaminationScore = totalScore };

				_ExaminationProvider.CreateRLTUserAndExamination(theUserAndExmt);
				if(lstUserAndExmtAswr != null && lstUserAndExmtAswr.Count > 0)
				{
					_ExaminationProvider.CreateRLTUserAndExaminationAnswer(lstUserAndExmtAswr);
				}

				BindCurrentExamination();
			}
		}

		protected void rptExmtQstn_ItemDataBound(object sender, RepeaterItemEventArgs e)
		{
			if(e.Item.DataItem != null)
			{
				var dataItem = e.Item.DataItem as ExaminationQuestion;
				var hfExmtQstnID = e.Item.FindControl("hfExmtQstnID") as HiddenField;

				hfExmtQstnID.Value = dataItem.ExaminationQuestionID.ToString();

				var rblExmtQstnAswr = e.Item.FindControl("rblExmtQstnAswr") as System.Web.UI.WebControls.RadioButtonList;
				if(_DicExmtQstnExmtAswr != null && _DicExmtQstnExmtAswr.Count > 0 && _DicExmtQstnExmtAswr.Keys.Contains(dataItem.ExaminationQuestionID))
				{
					rblExmtQstnAswr.DataSource = _DicExmtQstnExmtAswr[dataItem.ExaminationQuestionID];
					rblExmtQstnAswr.DataBind();
				}

				if(UsersExamination != null)
				{
					var lblExmtQstnRightAswr = e.Item.FindControl("lblExmtQstnRightAswr") as System.Web.UI.WebControls.Label;

					lblExmtQstnRightAswr.Text = "(正确答案: " + dataItem.ExaminationQuestionAnswer + ")";

					var exmtQstnAswr = _DicExmtQstnExmtAswr[dataItem.ExaminationQuestionID];

					if(exmtQstnAswr != null && exmtQstnAswr.Count > 0)
					{
						var exmtQstnAswrID = exmtQstnAswr.Select(ea => ea.ExaminationAnswerID).ToList();

						if(_UsersExmtAswr != null && _UsersExmtAswr.Count > 0)
						{
							var selectedAnswer = _UsersExmtAswr.Intersect(exmtQstnAswrID).FirstOrDefault();
							foreach(ListItem item in rblExmtQstnAswr.Items)
							{
								item.Selected = (item.Value.Equals(selectedAnswer.ToString()));
							}
						}
					}
				}
			}
		}

		private void BindCurrentExamination()
		{
			if(CurrentExaminationID > 0)
			{
				if(_ExaminationProvider == null)
				{
					_ExaminationProvider = new ExaminationProvider();
				}

				var theExmt = _ExaminationProvider.GetExamination(CurrentExaminationID);

				if(theExmt != null)
				{
					//RLT_UserAndExamination theUserExmt = GetUsersExamination();

					if(UsersExamination != null)
					{
						divexmttips.Visible = false;
						divexmtresult.Visible = true;
						ltrExmtTotalScore1.Text = "0";
						ltrExmtTime1.Text = theExmt.ExaminationTime.ToString();
						ltrExmtScore.Text = _UsersExamination.ExaminationScore.ToString();
						btnSubmit.Visible = false;
					}
					else
					{
						divexmttips.Visible = true;
						divexmtresult.Visible = false;
						this.ltrExmtTime.Text = theExmt.ExaminationTime.ToString();
						this.ltrExmtTotalScore.Text = "0";
						this.lblTime.Text = theExmt.ExaminationTime.ToString() + ":00";
						btnSubmit.Visible = true;
					}

					this.ltrExmtName.Text = theExmt.ExaminationName;

					var lstAllExmtQstn = _ExaminationProvider.GetExaminationQuestionByExamination(CurrentExaminationID);
					List<ExaminationQuestion> lstExmtQstn = null;
					if(lstAllExmtQstn != null)
					{
						if(lstAllExmtQstn.Count <= 100)
						{
							lstExmtQstn = lstAllExmtQstn;
						}
						else
						{
							lstExmtQstn = GetRandom100Questions(lstAllExmtQstn);
						}
					}
					var lstExmtAswr = _ExaminationProvider.GetExaminationAnswerByExamination(CurrentExaminationID);

					if(lstExmtQstn != null && lstExmtQstn.Count > 0)
					{
						_DicExmtQstnExmtAswr = new Dictionary<int, List<ExaminationAnswer>>();

						var totalScore = decimal.Zero;

						foreach(var eq in lstExmtQstn)
						{
							var qas = lstExmtAswr.Where(qa => qa.ExaminationQuestionID == eq.ExaminationQuestionID);

							if(qas != null)
							{
								_DicExmtQstnExmtAswr.Add(eq.ExaminationQuestionID, qas.ToList());
							}

							totalScore += eq.ExaminationQuestionScore.GetValueOrDefault(0);
						}

						if(SiteContext.Current.CurrentUser != null)
						{
							var userExmtAswr = _ExaminationProvider.GetUsersExaminationAnswer(SiteContext.Current.CurrentUser.UserID);
							if(userExmtAswr != null && userExmtAswr.Count > 0)
							{
								_UsersExmtAswr = userExmtAswr.Select(ue => ue.ExaminationAnswerID).ToList();
							}

							if(UsersExamination != null)
							{
								ltrExmtTotalScore1.Text = totalScore.ToString();
							}
							else
							{
								ltrExmtTotalScore.Text = totalScore.ToString();
							}
						}
					}

					rptExmtQstn.DataSource = lstExmtQstn;
					rptExmtQstn.DataBind();
				}
			}
		}

		private List<ExaminationQuestion> GetRandom100Questions(List<ExaminationQuestion> lstExmtQst)
		{
			List<ExaminationQuestion> result = null;

			if(lstExmtQst != null && lstExmtQst.Count > 0)
			{
				result = new List<ExaminationQuestion>();

				Random r = new Random();

				while(result.Count < 100)
				{
					var randomIndex = r.Next(0, lstExmtQst.Count);

					if(!result.Contains(lstExmtQst[randomIndex]))
					{
						result.Add(lstExmtQst[randomIndex]);
					}
				}
			}

			return result;
		}

		//private RLT_UserAndExamination GetUsersExamination()
		//{
		//  RLT_UserAndExamination rltUserAndExmt = null;

		//  var user = SiteContext.Current.CurrentUser;

		//  if(user != null && CurrentExaminationID > 0)
		//  {
		//    if(_ExaminationProvider == null)
		//    {
		//      _ExaminationProvider = new ExaminationProvider();
		//    }

		//    var rlt_UserAndExmt = _ExaminationProvider.GetUserAndExaminationByUser(user.UserID);

		//    if(rlt_UserAndExmt != null && rlt_UserAndExmt.Count > 0)
		//    {
		//      rltUserAndExmt = rlt_UserAndExmt.SingleOrDefault(ue => ue.ExaminationID == CurrentExaminationID);
		//    }
		//  }

		//  return rltUserAndExmt;
		//}
	}
}